package com.zmn.oms.business.impl.product;

import com.google.common.collect.Lists;
import com.zmn.manager.redis.lock.DistributedLock;
import com.zmn.manager.redis.lock.DistributedLockUtils;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.common.constant.LockConsts;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.exception.OmsBusinessException;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import io.shardingsphere.api.HintManager;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 类描述：订单产品扩展
 *
 * @author lujia
 * @date 2018/12/18 14:38
 */
@Service
public class OrderProductExtendBServiceImpl implements OrderProductExtendBService {

    private Logger logger = LoggerFactory.getLogger(OrderProductExtendBServiceImpl.class);
    
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderWarrantyService orderWarrantyService;
    @Autowired
    OrderServiceItemService orderServiceItemService;
    @Autowired
    OrderProductExtendService orderProductExtendService;

    @Override
    public List<OrderProductExtend> getOrderProductExtend(Long orderId) {
        List<OrderProductExtend> extendList = orderProductExtendService.listByOrderIdSrcMaster(orderId);
        if (CollectionUtils.isNotEmpty(extendList)) {
            return extendList;
        }

        // 分布式锁
        String lockKey = String.format(LockConsts.REDIS_LOCK_KEY_PRODUCT_EXTEND_FORMAT, orderId);
        DistributedLock distributedLock = DistributedLockUtils.build(lockKey);
        if (!distributedLock.lock()) {
            logger.error("产品处理扩展异常，没有获取到分布式锁 orderId：{}", orderId);
            throw new OmsBusinessException("产品处理扩展异常，请稍后再试！");
        }

        extendList = orderProductExtendService.listByOrderIdSrcMaster(orderId);
        if (CollectionUtils.isNotEmpty(extendList)) {
            try {
                distributedLock.unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return extendList;
        }
        try {
            extendList = this.createOrderProductExtend(orderId);
        } catch (Exception ex){
            logger.error("生成产品扩展异常，orderId：{}", orderId);
            logger.error("生成产品扩展异常", ex);
        } finally {
            try {
                distributedLock.unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return extendList;
    }

    /**
     * 生成订单产品扩展
     *
     * @param orderId
     */
    private List<OrderProductExtend> createOrderProductExtend(Long orderId){
        List<OrderProduct> orderProducts = orderProductService.listOrderProductByOrderIdSrcMaster(orderId);
        if (CollectionUtils.isEmpty(orderProducts)) {
            logger.error("工单产品不存在{}",orderId);
            return null;
        }

        List<OrderProductExtend> extendList = Lists.newArrayList();
        for (OrderProduct orderProduct : orderProducts) {
            for (Integer i = 0; i < orderProduct.getNumber(); i++) {
                OrderProductExtend orderProductExtend = new OrderProductExtend();
                orderProductExtend.setOrderId(orderProduct.getOrderId());
                orderProductExtend.setProductId(orderProduct.getProductId());
                orderProductExtend.setProductName(orderProduct.getProductName());
                orderProductExtend.setShowProductId(orderProduct.getShowProductId());
                orderProductExtend.setShowProductName(orderProduct.getShowProductName());
                orderProductExtend.setCreateTime(new Date());
                extendList.add(orderProductExtend);
            }
        }

        // 删除产品扩展表，订单服务项, 保修卡
        // 删产品扩展表
        orderProductExtendService.deleteByOrderId(orderId);
        // 删订单服务项
        orderServiceItemService.deleteByOrderId(orderId);
        // 删订单保修项
        orderWarrantyService.deleteByOrderId(orderId);

        // 后增产品扩展表
        orderProductExtendService.insertAll(extendList);

        return extendList;
    }

    /**
     * 通过订单ID和旧的产品ID改产品ID和产品名称
     * @param orderProductExtend
     * @return
     */
    public int updateByOrderIdAndOldProductId(OrderProductExtend orderProductExtend) {
        return orderProductExtendService.updateByOrderIdAndOldProductId(orderProductExtend);
    }
}
